package com.bw.dao;

import com.bw.pojo.Elepro;
import com.bw.util.JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/***************************
 FileAction:

 CreateTime:2022-04-12 11:01
 Author:Aaking-aline
 ****************************/
public class EleproDao {

    public List<Elepro> selectElepro(String page) throws SQLException {
        int index = ((Integer.parseInt(page) - 1) * 5);

        String sql = "select * from elepro limit " + index + ",5";

        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        List<Elepro> list = new ArrayList<>();

        while(rs.next()){
            Elepro elepro = new Elepro(rs.getInt(1),
                    rs.getString(2),
                    rs.getString(3),
                    rs.getDouble(4),
                    rs.getInt(5),
                    rs.getString(6),
                    rs.getString(7),
                    rs.getString(8));
            list.add(elepro);
        }

        return list;
    }


    public int selectNum() throws SQLException {
        String sql = "select count(*) from elepro";

        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        if(rs.next()){
            return rs.getInt(1);
        }
        return 0;
    }

    public void insertElepro(Elepro elepro) throws SQLException {
        String sql = "insert into elepro values(null,?,?,?,?,?,?,?)";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setObject(1,elepro.getElepro_name());
        ps.setObject(2,elepro.getElepro_kind());
        ps.setObject(3,elepro.getElepro_price());
        ps.setObject(4,elepro.getElepro_stock());
        ps.setObject(5,elepro.getElepro_make_date());
        ps.setObject(6,elepro.getElepro_make_addr());
        ps.setObject(7,elepro.getElepro_IMEI());

        ps.executeUpdate();
    }

    public void deleteElepro(String id) throws SQLException {

        String sql = "delete from elepro where id in(" + id + ")";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.executeUpdate();
    }
}
